<template>
  <div class="dashboard">
    <div class="charts-one">
      <h1>今日数据</h1>
      <div class="box-group">
        <div class="title-wrapper">
          <span class="title">消耗</span>
          <div class="bot-group">
            <span class="price">{{ (toDayData.totalIncome > 0 ? toDayData.totalIncome / 10000 : 0).toFixed(2) }}</span>
            <span class="value">元</span>
          </div>
        </div>
        <div class="title-wrapper">
          <span class="title">活动访问</span>
          <div class="bot-group">
            <span class="price">{{ toDayData.totalSlotPv || 0 }}</span>
            <span class="value">次</span>
          </div>
        </div>
        <div class="title-wrapper">
          <span class="title">广告曝光</span>
          <div class="bot-group">
            <span class="price">{{ toDayData.totalAdvertShowPv || 0 }}</span>
            <span class="value">次</span>
          </div>
        </div>
        <div class="title-wrapper">
          <span class="title">有效点击</span>
          <div class="bot-group">
            <span class="price">{{ toDayData.totalAdvertClick || 0 }}</span>
            <span class="value">次</span>
          </div>
        </div>
        <div class="title-wrapper">
          <span class="title">点击率</span>
          <div class="bot-group">
            <span class="price">{{
              (
                (toDayData.totalAdvertClick / toDayData.totalAdvertShowPv >= 0
                  ? toDayData.totalAdvertClick / toDayData.totalAdvertShowPv
                  : 0) * 100
              ).toFixed(2)
            }}</span>
            <span class="value">%</span>
          </div>
        </div>
      </div>
      <a-spin size="large" :spinning="splinLoading" tip="图表加载中..."> </a-spin>
      <div id="myChart" :style="{ width: '100%', height: '500px' }"></div>
    </div>
    <div class="charts-one">
      <!-- <h1>近期数据</h1> -->
      <div class="header">
        <div>
          <span class="title" @click="changeCharts(0)" :style="[{ color: active == 0 ? '#3AA1FF' : '' }]">近期数据</span>
          <span class="title" @click="changeCharts(1)" :style="[{ color: active == 1 ? '#3AA1FF' : '' }]">收益波动分析</span>
        </div>
        <a-select
          :loading="homePageDataNearlyLoading"
          :default-value="0"
          style="width: 120px"
          @change="handleDateChange"
          v-show="active == 0"
        >
          <a-select-option :value="0">
            过去7天
          </a-select-option>
          <a-select-option :value="1">
            过去15天
          </a-select-option>
          <a-select-option :value="2">
            过去30天
          </a-select-option>
        </a-select>
      </div>
      <div class="media-box">
        <a-select
          :loading="homePageDataNearlyLoading"
          default-value="0"
          style="width: 120px"
          @change="handleChange"
          v-show="active == 0"
          placeholder="请选择媒体"
        >
          <a-select-option v-for="items in mediaSelectList" :key="items.appKey" :value="items.appKey">
            {{ items.appName }}
          </a-select-option>
        </a-select>
        <div class="box-group2" v-show="active == 0">
          <div class="title-wrapper">
            <span class="title">PV</span>
            <div class="bot-group">
              <countTo class="price" :startVal="startVal" :endVal="nearlyData.totalSlotPv || 0" :duration="2000" />
              <span class="value">次</span>
            </div>
          </div>
          <div class="title-wrapper">
            <span class="title">UV</span>
            <div class="bot-group">
              <countTo class="price" :startVal="startVal" :endVal="nearlyData.totalActivityShowUv || 0" :duration="2000" />
              <span class="value">个</span>
            </div>
          </div>
          <div class="title-wrapper">
            <span class="title">活动参与</span>
            <div class="bot-group">
              <countTo class="price" :startVal="startVal" :endVal="nearlyData.totalActivityJoinPv || 0" :duration="2000" />
              <span class="value">次</span>
            </div>
          </div>
          <div class="title-wrapper">
            <span class="title">广告曝光</span>
            <div class="bot-group">
              <countTo class="price" :startVal="startVal" :endVal="nearlyData.totalAdvertShowPv || 0" :duration="2000" />
              <span class="value">次</span>
            </div>
          </div>
          <div class="title-wrapper">
            <span class="title">有效点击</span>
            <div class="bot-group">
              <countTo class="price" :startVal="startVal" :endVal="nearlyData.totalAdvertClick || 0" :duration="2000" />
              <span class="value">次</span>
            </div>
          </div>
          <div class="title-wrapper">
            <span class="title">预估收入</span>
            <div class="bot-group">
              <countTo
                class="price"
                :startVal="startVal"
                :decimals="2"
                :endVal="nearlyData.totalIncome >= 0 ? nearlyData.totalIncome / 10000 : 0"
                :duration="2000"
              ></countTo>
              <span class="value">元</span>
            </div>
          </div>
        </div>
      </div>

      <!-- <div id="c2"></div> -->
      <div v-show="active == 0">
        <div id="charts" :style="{ width: '100%', height: '500px' }"></div>
      </div>
      <div v-show="active == 1">
        <div class="wrapper">
          <div>
            <span>收益波动分析</span>
            <a-icon type="arrow-up" />
            <a-icon type="arrow-down" />
          </div>
          <span>{{ toDay }} </span>
        </div>
        <a-table :rowKey="(record) => record.income" :pagination="false" :columns="incomeColumns" :data-source="incomeData">
          <span slot="income" slot-scope="_, record">
            <span>{{ (record.income / 10000).toFixed(2) || 0 }}</span>
          </span>
          <span slot="income1" slot-scope="_, record">
            <span>{{ (record.income1 / 10000).toFixed(2) || 0 }}</span>
          </span>
          <span slot="changeValue" slot-scope="_, record">
            <span v-if="record.income - record.income1 > 0">
              {{ `+${(record.income / 10000 - record.income1 / 10000).toFixed(2)}元` }}
              <a-icon style="color:#3AA1FF" type="arrow-up" />
            </span>
            <span v-if="record.income - record.income1 <= 0">
              {{ `${(record.income / 10000 - record.income1 / 10000).toFixed(2)}元` }}
              <a-icon style="color:#3AA1FF" type="arrow-down" />
            </span>
          </span>
          <span slot="chainRate" slot-scope="_, record">
            <span v-if="record.income2 == 0">-</span>
            <span v-else>{{ (((record.income - record.income2) / record.income2) * 100).toFixed(2) }}%</span>
          </span>
        </a-table>
        <div class="wrapper">
          <div>
            <span>PV波动分析</span>
            <a-icon type="arrow-up" />
            <a-icon type="arrow-down" />
          </div>
          <span>{{ toDay }} </span>
        </div>
        <a-table :rowKey="(record) => record.income" :pagination="false" :columns="PVColumns" :data-source="incomeData">
          <span slot="pv" slot-scope="_, record">
            <span>{{ record.pv || 0 }}</span>
          </span>
          <span slot="pv1" slot-scope="_, record">
            <span>{{ record.pv1 || 0 }}</span>
          </span>
          <span slot="changeValue" slot-scope="_, record">
            <span v-if="record.pv - record.pv1 > 0">
              {{ `+${record.pv - record.pv1}` }}
              <a-icon style="color:#3AA1FF" type="arrow-up" />
            </span>
            <span v-if="record.pv - record.pv1 <= 0">
              {{ `${record.pv - record.pv1}` }}
              <a-icon style="color:#3AA1FF" type="arrow-down" />
            </span>
          </span>
          <span slot="chainRate" slot-scope="_, record">
            <span v-if="record.pv2 == 0">-</span>
            <span v-else>{{ (((record.pv - record.pv2) / record.pv2) * 100).toFixed(2) }}%</span>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import countTo from 'vue-count-to'
import { incomeColumns, PVColumns } from './table'
import { getHomePageDataToday, getHomePageDataNearly, getHomePageDataIncomeAnalyse } from '@/api/dashboard/api'
import { getAppList } from '@/api/MeidaMan/api'
export default {
  name: 'dashboard',
  components: {
    countTo,
  },
  data() {
    return {
      dayjs,
      incomeColumns,
      PVColumns,
      incomeData: [],
      active: 0,
      startVal: 0,
      toDayData: {},
      nearlyData: {},
      mediaSelectList: [],
      homePageDataNearlyLoading: false,
      appKey: '',
      splinLoading: false,
      dateObj: {
        startTime: dayjs(dayjs().format('YYYY-MM-DD'))
          .subtract(7, 'days')
          .valueOf(),
        endTime: dayjs(dayjs().format('YYYY-MM-DD')).valueOf(),
      },
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.homePageDataToday()
      this.homePageDataNearly({})
      this.homePageDataIncomeAnalyse()
      this.appList({})
    })
    // 下面代码解决第一次渲染，图标宽度过款问题
    const e = document.createEvent('Event')
    e.initEvent('resize', true, true)
    window.dispatchEvent(e)
  },
  computed: {
    toDay() {
      return `数据截止日期 ${dayjs().format(`YYYY年MM月DD日`)}`
    },
  },
  methods: {
    /**
     * 收益波动分析
     */
    async homePageDataIncomeAnalyse() {
      const [err, data] = await getHomePageDataIncomeAnalyse()
      if (!err) {
        console.log('--------------------')
        console.log({ data })
        this.incomeData = data
      } else {
        console.log('--------------------')
        console.log({ err })
        this.$msgErr(err)
      }
    },
    /**
     * @func 媒体列表数据
     */
    appList(param) {
      getAppList({ param })
        .then((res) => {
          const list = res?.data?.data?.list ?? []
          list.unshift({
            appName: '全部媒体',
            appKey: '0',
          })
          this.mediaSelectList = list
        })
        .catch((err) => {
          this.$msgErr(err)
        })
    },
    /**
     * @func 今日数据
     */
    async homePageDataToday() {
      this.splinLoading = true
      const [err, data] = await getHomePageDataToday()
      if (!err) {
        this.splinLoading = false
        const { perData, ...param } = data
        this.toDayData = param
        const incomeArr = []
        const activityJoinPvArr = []
        const activityShowUvArr = []
        const advertClickArr = []
        const avertShowPvArr = []
        const dateTimeArr = []
        const slotPvArr = []
        const percentClickArr = []
        for (const items in perData) {
          if (Object.hasOwnProperty.call(perData, items)) {
            const { income, activityJoinPv, activityShowUv, advertClick, avertShowPv, dateTime, slotPv } = perData[items]
            incomeArr.push(income / 10000 ?? [])
            activityJoinPvArr.push(activityJoinPv ?? [])
            activityShowUvArr.push(activityShowUv ?? [])
            advertClickArr.push(advertClick ?? [])
            avertShowPvArr.push(avertShowPv ?? [])
            dateTimeArr.push(dayjs(Number(dateTime)).format('HH:mm') ?? [])
            slotPvArr.push(slotPv ?? [])
            percentClickArr.push(((advertClick / avertShowPv >= 0 ? advertClick / avertShowPv : 0) * 100).toFixed(2))
          }
        }
        this.randerCharts(incomeArr, slotPvArr, avertShowPvArr, advertClickArr, percentClickArr, dateTimeArr)
      } else {
        this.splinLoading = false
        this.$msgErr(err)
      }
    },
    isNumber(obj) {
      var reg = /^[0-9]+.?[0-9]*$/
      if (reg.test(obj)) {
        return true
      }
      return false
    },
    /**
     * @func 近日数据
     */
    async homePageDataNearly(param) {
      this.homePageDataNearlyLoading = true
      const [err, data] = await getHomePageDataNearly({ ...param })
      if (!err) {
        const { perData, ...param } = data
        this.nearlyData = param
        const slotPvArr = []
        const activityShowUvArr = []
        const avertShowPvArr = []
        const activityJoinPvArr = []
        const advertClickArr = []
        const dateTimeArr = []
        const incomeArr = []
        const uvJoinArr = []
        const reallyClickArr = []
        for (const items in perData) {
          if (Object.hasOwnProperty.call(perData, items)) {
            const { slotPv, activityShowUv, avertShowPv, activityJoinPv, advertClick, income, dateTime } = perData[items]
            slotPvArr.push(slotPv ?? [])
            activityShowUvArr.push(activityShowUv ?? [])
            activityJoinPvArr.push(activityJoinPv ?? [])
            avertShowPvArr.push(avertShowPv ?? [])
            advertClickArr.push(advertClick ?? [])
            incomeArr.push((income / 10000).toFixed(2) ?? [])
            dateTimeArr.push(dayjs(Number(dateTime)).format('MM-DD') ?? [])
            console.log({ activityJoinPv, activityShowUv })
            if (activityJoinPv == 0 || activityShowUv == 0) {
              uvJoinArr.push(0)
            } else {
              uvJoinArr.push(((activityJoinPv / activityShowUv) * 100).toFixed(2))
            }
            if (advertClick == 0 || avertShowPv == 0) {
              reallyClickArr.push(0)
            } else {
              reallyClickArr.push(((advertClick / avertShowPv) * 100).toFixed(2))
            }
          }
        }
        this.renderDataNearly(
          slotPvArr,
          activityShowUvArr,
          dateTimeArr,
          avertShowPvArr,
          activityJoinPvArr,
          advertClickArr,
          incomeArr,
          uvJoinArr,
          reallyClickArr,
        )
        this.homePageDataNearlyLoading = false
      } else {
        this.$msgErr(err)
        this.homePageDataNearlyLoading = false
      }
    },
    /**
     * @func 近期数据图切换
     */
    changeCharts(current) {
      this.active = current
    },
    /**
     * @func 媒体选框
     */
    handleChange(value) {
      const appKey = value
      this.appKey = appKey
      const { startTime, endTime } = this.dateObj
      console.log(startTime)
      console.log(endTime)
      this.homePageDataNearly({ startTime, endTime, appKey })
    },
    /**
     * @func 时间选择
     */
    handleDateChange(value) {
      const appKey = this.appKey
      const endTime = dayjs(dayjs().format('YYYY-MM-DD')).valueOf()
      if (value == 0) {
        const startTime = dayjs(dayjs().format('YYYY-MM-DD'))
          .subtract(7, 'days')
          .valueOf()
        this.dateObj = { startTime, endTime }
        this.homePageDataNearly({ startTime, endTime, appKey })
      } else if (value == 1) {
        const startTime = dayjs(dayjs().format('YYYY-MM-DD'))
          .subtract(15, 'days')
          .valueOf()
        this.dateObj = { startTime, endTime }
        this.homePageDataNearly({ startTime, endTime, appKey })
      } else if (value == 2) {
        const startTime = dayjs(dayjs().format('YYYY-MM-DD'))
          .subtract(30, 'days')
          .valueOf()
        this.dateObj = { startTime, endTime }
        this.homePageDataNearly({ startTime, endTime, appKey })
      }
    },
    /**
     * @func 今日数据-图表渲染
     */
    randerCharts(incomeArr = [], slotPvArr = [], avertShowPvArr = [], advertClickArr = [], percentClickArr = [], dateTimeArr = []) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById('myChart'))
      myChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        legend: {
          orient: 'horizontal', // 'vertical'
          selected: {
            '活动访问（次）': false,
            '有效点击（次）': false,
            '点击率（%）': false,
          },
          data: ['消耗（元）', '活动访问（次）', '广告曝光（次）', '有效点击（次）', '点击率（%）'],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: dateTimeArr,
          },
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [
          {
            name: '消耗（元）',
            type: 'bar',
            emphasis: {
              focus: 'series',
            },
            data: incomeArr,
          },
          {
            name: '活动访问（次）',
            type: 'bar',
            emphasis: {
              focus: 'series',
            },
            data: slotPvArr,
          },
          {
            name: '广告曝光（次）',
            type: 'bar',
            emphasis: {
              focus: 'series',
            },
            data: avertShowPvArr,
          },
          {
            name: '有效点击（次）',
            type: 'bar',
            color: '#E9967A',
            emphasis: {
              focus: 'series',
            },
            data: advertClickArr,
          },
          {
            name: '点击率（%）',
            type: 'bar',
            data: percentClickArr,
            emphasis: {
              focus: 'series',
            },
          },
        ],
      })

      window.addEventListener('resize', function() {
        myChart.resize()
      })
    },
    /**
     * @func 近期数据-图表渲染
     */
    renderDataNearly(
      slotPvArr,
      activityShowUvArr,
      dateTimeArr,
      avertShowPvArr,
      activityJoinPvArr,
      advertClickArr,
      incomeArr,
      uvJoinArr,
      reallyClickArr,
    ) {
      let charts = this.$echarts.init(document.getElementById('charts'))
      charts.setOption({
        /*  title: {
          text: '折线图堆叠',
        }, */
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          orient: 'horizontal', // 'vertical'
          selected: {
            '每UV参与（%）': false,
            '点击率（%）': false,
          },
          data: [
            'PV（次）',
            'UV（个）',
            '活动参与（次）',
            '每UV参与（%）',
            '广告曝光（次）',
            '有效点击（次）',
            '点击率（%）',
            '预估收入（元）',
          ],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateTimeArr,
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: 'PV（次）',
            type: 'line',
            smooth: true,
            data: slotPvArr,
          },
          {
            name: 'UV（个）',
            type: 'line',
            smooth: true,
            data: activityShowUvArr,
          },
          {
            name: '活动参与（次）',
            type: 'line',
            smooth: true,
            data: activityJoinPvArr,
          },
          {
            name: '每UV参与（%）',
            type: 'line',
            smooth: true,
            data: uvJoinArr,
          },
          {
            name: '广告曝光（次）',
            type: 'line',
            smooth: true,
            data: avertShowPvArr,
          },
          {
            name: '有效点击（次）',
            type: 'line',
            smooth: true,
            data: advertClickArr,
          },
          {
            name: '点击率（%）',
            type: 'line',
            smooth: true,
            data: reallyClickArr,
          },
          {
            name: '预估收入（元）',
            type: 'line',
            smooth: true,
            data: incomeArr,
          },
        ],
      })
      window.addEventListener('resize', function() {
        charts.resize()
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.box-group {
  display: flex;
  width: 90%;
  justify-content: space-between;
  padding-bottom: 50px;
  .title-wrapper {
    display: flex;
    flex-direction: column;
    height: 50px;
    justify-content: space-between;
    color: rgb(24, 144, 255);
    .bot-group {
      .title {
        font-size: 16px;
      }
      .price {
        font-size: 1vw;
      }
    }
  }
}
.box-group2 {
  display: flex;
  width: 90%;
  justify-content: space-between;
  padding: 0 0 50px 50px;
  .title-wrapper {
    display: flex;
    flex-direction: column;
    height: 50px;
    justify-content: space-between;
    color: rgb(24, 144, 255);
    .bot-group {
      .title {
        font-size: 16px;
      }
      .price {
        font-size: 1vw;
      }
    }
  }
}

.wrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px 0;
}
#c1 {
  padding-left: 20px;
  box-sizing: border-box;
  margin-top: 100px;
}
#c2 {
  padding-left: 20px;
  box-sizing: border-box;
  margin-top: 100px;
}
.charts-one {
  padding: 50px;
}
.media-box {
  margin: 20px 0 0 60px;
  display: flex;
}
.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .title {
    font-size: 28px;
    font-weight: 500;
    color: #000000;
    &:first-child {
      margin-right: 40px;
    }
  }
}
</style>
